package com.fegin.api;

import com.fegin.api.service.Product;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:RenPu
 * @Date: 2020/10/27 17:42
 * @Version: 1.0
 * @description: fegin控制层，仅供gateway测试用
 */

@RestController
@RequestMapping("gateway")
public class GatewayController {

    public static final Map<Long, Product> items = new ConcurrentHashMap<>();


    /**
     * 发布商品和获取商品的接口
     *
     * @param pId
     * @return
     */

    @RequestMapping(value = "detials", method = RequestMethod.GET)
    @ResponseBody
    public Product getProduct(@RequestParam("pId") Long pId) {


        if (!items.containsKey(pId)) {
            Product product1 = Product.builder()
                    .productId(pId)
                    .desc("好吃不贵！！！")
                    .stock(100L)
                    .build();

            //在此不直接进行put，而是putIfAbsent的操作防止多线程的不安全性
            items.putIfAbsent(pId, product1);
        }

        return items.get(pId);

    }


    @RequestMapping(value = "placeOrder", method = RequestMethod.POST)
    public String buy(@RequestParam("pId") Long pId) {

        Product product = items.get(pId);

        if (product == null) {
            return "Product not Found";
        } else if (product.getStock() <= 0L) {
            return "Sold out";
        }


        //在此使用锁防止，俩个线程同时进入，减库的操作，此时库里只有一个商品 就会导致超卖的现象
        synchronized (product) {
            if (product.getStock() <= 0L) {
                return "Sold out";
            }
            product.setStock(product.getStock() - 1);
        }

        return "place order";


    }


}
